package com.example.mystore.servlets.service;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

public class CheckServlet extends HttpServlet {

    private static int WIDTH = 100;
    private static int HEIGHT = 50;

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        resp.setContentType("image/jpeg");
        ServletOutputStream sos = resp.getOutputStream();
        resp.setHeader("pragma","No-cache");
        resp.setDateHeader("Expires",0);
        BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_BGR);
        Graphics graphics = image.getGraphics();
        char[] rands = generateCheckCode();
        drawBackground(graphics);
        drawRands(graphics,rands);
        graphics.dispose();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image,"JPEG",bos);
        byte[] buf = bos.toByteArray();
        resp.setContentLength(buf.length);
        sos.write(buf);
        bos.close();
        sos.close();
        session.setAttribute("check_code",new String(rands));
    }

    private void drawRands(Graphics graphics, char[] rands) {

        graphics.setColor(Color.black);

        Random random = new Random(5);
        int size = random.nextInt(9)+21;
        graphics.setFont(new Font(null,Font.ITALIC|Font.BOLD,size));
        graphics.drawString(""+rands[0],10,33);
        graphics.drawString(""+rands[1],30,30);
        graphics.drawString(""+rands[2],50,32);
        graphics.drawString(""+rands[3],70,29);
    }

    private void drawBackground(Graphics graphics) {
        graphics.setColor(new Color(0XDCDCDC));
        graphics.fillRect(0,0,WIDTH,HEIGHT);
        for (int i=0;i<120;i++){
            int x=(int)(Math.random()*WIDTH);
            int y=(int)(Math.random()*HEIGHT);
            int red=(int)(Math.random()*255);
            int green=(int)(Math.random()*255);
            int blue=(int)(Math.random()*255);

            graphics.setColor(new Color(red,green,blue));
            graphics.drawOval(x,y,1,0);
        }
    }


    private char[] generateCheckCode() {
        String chars="1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
        char[] rands = new char[4];
        for (int i=0;i<4;i++){
            int rand=(int)(Math.random()*chars.length());
            rands[i]=chars.charAt(rand);
        }
        return rands;
    }
}